package com.movecar.ui;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import BLLocationCallbacker.DialogItemSelectCallbacker;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.movecar.R;
import com.movecar.dialog.MoveCarDialogBuilder;
import com.movecar.model.SelfInfoBean;
import com.movecar.model.UserIconBean;
import com.movecar.utils.Alert;
import com.movecar.utils.AppConfig;
import com.movecar.utils.BitMapUtil;
import com.movecar.utils.BitmapCropper;
import com.movecar.utils.DataStore;
import com.movecar.utils.FileProvider;
import com.movecar.utils.HttpPostRequestAsyncTask;
import com.movecar.utils.PopupWindowAnimation;
import com.movecar.utils.RequestResultCallback;
import com.movecar.utils.imageloader.Constants;
import com.movecar.widget.CustomProgressDialog;
import com.nostra13.universalimageloader.core.ImageLoader;

/**
 * 更多-个人信息
 * 
 * @author Zhao.JQ
 * 
 */
public class PersonalInfActivity extends Activity implements OnClickListener, DialogItemSelectCallbacker {

	private CustomProgressDialog progressDialog = null;
	private EditText mEditTextCalled, address;
	private InputMethodManager imm;
	private ImageView user_photo;
	private SelfInfoBean mInfoBean;
	private UserIconBean mUserIconBean;
	private ImageLoader imageLoader = null;
	private String upLoadPic = "";
	private AlertDialog mDialogChoosePicture;
	/* 选择图片 */
	private static final int PICK = 0x11;
	/* 切割图片 */
	private static final int CROP = 0x12;
	/** 新相片文件 */
	private File rFilePicture = null;
	/** 相片临时文件 */
	private File rFileTemporary = null;
	private final ArrayList<String> mListImageFile = new ArrayList<String>();
	private RelativeLayout user_photo_relative;
	private View mainView;
	private LayoutInflater layoutInflater;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);mainView = layoutInflater.inflate(R.layout.more_personal_information, null);
		setContentView(mainView);
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imageLoader = ImageLoader.getInstance();
		// imageLoader.init(Constants.imageLoaderConfiguration(this));
		initView();
	}

	private void initView() {
		mEditTextCalled = (EditText) findViewById(R.id.user_nick_name);
		address = (EditText) findViewById(R.id.address);
		user_photo = (ImageView) findViewById(R.id.user_photo);

		user_photo_relative = (RelativeLayout) findViewById(R.id.user_photo_relative);
		user_photo_relative.setOnClickListener(this);
		Button back = (Button) findViewById(R.id.btn_left);
		back.setVisibility(View.VISIBLE);
		back.setOnClickListener(this);
		findViewById(R.id.ok).setOnClickListener(this);
		TextView title = (TextView) findViewById(R.id.title);
		title.setText("个人资料");

		querySelfInfo();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_left:
			imm.hideSoftInputFromWindow(mEditTextCalled.getWindowToken(), 0);
			finish();

			break;
		case R.id.ok:

			if (!"".equals(mEditTextCalled.getText().toString().trim())) {
				if (mEditTextCalled.getText().toString().trim().length() < 7) {
					startProgressDialog();
					saveSelfInfo();
				} else {
					Alert.error(this, "昵称不能大于6个字");
				}

			} else {
				Alert.error(this, "请输入昵称");
			}
			break;
		case R.id.user_photo_relative:
			(mDialogChoosePicture = MoveCarDialogBuilder.buidlListDialog(this, "", new String[] { "从相机拍照", "从图库挑选",
					"设置默认头像" }, this)).show();

			break;
		default:
			break;
		}

	}

	/**
	 * 获取用户头像地址
	 */
	@SuppressWarnings("unchecked")
	private void querySelfInfo() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "querySelfInfoNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				Gson gson = new Gson();
				try {
					mInfoBean = gson.fromJson(result, SelfInfoBean.class);
				} catch (Exception e) {
					return;
				}

				if ("".equals(mInfoBean.getError()) || null == mInfoBean.getError()) {
					if ("".equals(mInfoBean.getFail()) || null == mInfoBean.getFail()) {

						mEditTextCalled.setText(mInfoBean.getNickname());
						address.setText(mInfoBean.getAddress());
						if (mInfoBean.getIcon().contains("default")) {
							imageLoader.displayImage(AppConfig.HOST + mInfoBean.getIcon(), user_photo,
									Constants.image_display_options, AppConfig.animateListener);
						} else {
							imageLoader.displayImage(AppConfig.HOST + mInfoBean.getIcon(), user_photo,
									Constants.image_display_options_conner, AppConfig.animateListener);
						}

					} else {
						Alert.error(PersonalInfActivity.this, mInfoBean.getFail());
					}
				} else {
					Alert.error(PersonalInfActivity.this, mInfoBean.getError());
				}

			}

			@Override
			public void onFail(String exception) {
				Alert.error(PersonalInfActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.USER).execute(params);
	}

	/**
	 * 保存昵称等个人信息
	 * 
	 * @author Zhao.JQ
	 */
	@SuppressWarnings("unchecked")
	private void saveSelfInfo() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "saveSelfInfoNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		params.add(new BasicNameValuePair("nickName", mEditTextCalled.getText().toString().trim()));
		params.add(new BasicNameValuePair("icon", upLoadPic));
		params.add(new BasicNameValuePair("address", address.getText().toString().trim()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				if ("0".equals(result)) {
					stopProgressDialog();
					Alert.warn(PersonalInfActivity.this, "设置成功");
					SharedPreferences sharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
					Editor editor = sharedPreferences.edit();// 获取编辑器
					editor.putString("nickName", mEditTextCalled.getText().toString());
					editor.commit();
					DataStore.getInstance().setNickName(mEditTextCalled.getText().toString());
					setResult(RESULT_OK);
					finish();
				} else {
					stopProgressDialog();
					Alert.error(PersonalInfActivity.this, result);
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.error(PersonalInfActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.USER).execute(params);
	}

	/**
	 * 设置默认头像
	 * 
	 * @author Zhao.JQ
	 */
	@SuppressWarnings("unchecked")
	private void updateUserIcon() {

		List<NameValuePair> params = new ArrayList<NameValuePair>();
		// 使用NameValuePair来保存要传递的Post参数
		params.add(new BasicNameValuePair("cmd", "updateUserIconNew1"));
		// 添加要传递的参数
		params.add(new BasicNameValuePair("userId", DataStore.getInstance().getUserId()));
		new HttpPostRequestAsyncTask(new RequestResultCallback() {

			@Override
			public void onSuccess(Object object) {

				String result = (String) object;
				Gson gson = new Gson();
				try {
					mUserIconBean = gson.fromJson(result, UserIconBean.class);
				} catch (Exception e) {
					return;
				}
				if (null != mUserIconBean) {
					stopProgressDialog();
					if (!"".equals(mUserIconBean.getCoinAlert())) {
						new PopupWindowAnimation(mainView, PersonalInfActivity.this);
					}
					if (mUserIconBean.getIcon().contains("default")) {
						imageLoader.displayImage(AppConfig.HOST + mUserIconBean.getIcon(), user_photo,
								Constants.image_display_options, AppConfig.animateListener);
					} else {
						imageLoader.displayImage(AppConfig.HOST + mUserIconBean.getIcon(), user_photo,
								Constants.image_display_options_conner, AppConfig.animateListener);
					}

				} else {
					stopProgressDialog();
					Alert.error(PersonalInfActivity.this, result);
				}
			}

			@Override
			public void onFail(String exception) {
				stopProgressDialog();
				Alert.error(PersonalInfActivity.this, "与服务器连接失败，请检查网络");

			}
		}, DataStore.class, AppConfig.USER).execute(params);
	}

	@Override
	public void onClick(DialogInterface dialog, int which) {
		if (dialog == mDialogChoosePicture) {
			if (which == 0) {
				try {
					rFilePicture = FileProvider.getNewJpegFile();

					final Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
					intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(rFilePicture));
					intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
					startActivityForResult(intent, PersonalInfActivity.PICK);
				} catch (final IOException e) {
					Alert.warn(PersonalInfActivity.this, "无法完成拍照操作，请检查存储卡是否安装或空间已满。");
					rFilePicture = null;
				}
			} else if (which == 1) {
				final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
				intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
				// intent.setType("image/*");
				// intent.addCategory(Intent.CATEGORY_OPENABLE);
				startActivityForResult(intent, PersonalInfActivity.PICK);
			} else if (which == 2) {
				updateUserIcon();
			}
		}

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onActivityResult(int, int,
	 * android.content.Intent)
	 */
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PersonalInfActivity.PICK) {
			if (resultCode != Activity.RESULT_OK) {
				rFilePicture = null;
				return;
			}
			/* rFilePicture值为null表明是从相册挑选。 */
			if (rFilePicture == null) {
				rFilePicture = FileProvider.getFileByUri(this, data.getData());
			}

			try {
				rFileTemporary = FileProvider.getNewTemporaryFile();
				BitmapCropper.cropSquarePicture(this, rFilePicture, rFileTemporary, 1280, PersonalInfActivity.CROP);
			} catch (final IOException e) {
				Alert.warn(PersonalInfActivity.this, "无法完成拍照操作，请检查存储卡是否安装或空间已满。");
				rFileTemporary = null;
			}

			rFilePicture = null;
		} else if (requestCode == PersonalInfActivity.CROP) {
			if (resultCode != Activity.RESULT_OK) {
				if (rFileTemporary != null) {
					rFileTemporary.delete();
					rFileTemporary = null;
				}
				return;
			}
			rFileTemporary = FileProvider.getFileByUri(this, Uri.parse(data.getAction()));
			mListImageFile.add(rFileTemporary.getPath());
			user_photo.setImageBitmap(BitMapUtil.getRoundedCornerBitmap(BitMapUtil.getSuitableBitmap(rFileTemporary)));
			// 压缩图片上传
			ByteArrayOutputStream myStream = new ByteArrayOutputStream();
			BitMapUtil.getBitmapFromFile(rFileTemporary, 1280, 1280).compress(Bitmap.CompressFormat.JPEG, 60, myStream);
			byte[] myCopybyte = myStream.toByteArray();
			int myLength = myCopybyte.length;
			upLoadPic = Base64.encodeToString(myCopybyte, 0, myLength, Base64.DEFAULT);

			rFileTemporary = null;
		}

	}

	private void startProgressDialog() {
		if (progressDialog == null) {
			progressDialog = CustomProgressDialog.createDialog(this);
			progressDialog.setMessage("正在加载...");
		}

		progressDialog.show();
	}

	private void stopProgressDialog() {
		if (progressDialog != null) {
			progressDialog.dismiss();
			progressDialog = null;
		}
	}
}